package com.youlu.campus.service.activity.impl;

import com.youlu.campus.base.exception.BusinessException;
import com.youlu.campus.common.utils.ExcelUtil;
import com.youlu.campus.entity.*;
import com.youlu.campus.entity.domain.UserActivityTaskRankingAttachImport;
import com.youlu.campus.entity.enums.TaskBizType;
import com.youlu.campus.service.activity.ActivityService;
import com.youlu.campus.service.activity.UserActivityTaskRankingAttachService;
import com.youlu.campus.service.ranking.UserActivityPointDetailService;
import com.youlu.campus.service.ranking.UserActivityPointRankingProvinceService;
import com.youlu.campus.service.visitor.VisitorUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import java.io.ByteArrayInputStream;
import java.util.*;

@Slf4j
@Service
public class UserActivityTaskRankingAttachServiceImpl implements UserActivityTaskRankingAttachService {
    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private ActivityService activityService;


    @Autowired
    private UserActivityPointDetailService userActivityPointDetailService;

    @Autowired
    private UserActivityPointRankingProvinceService userActivityPointRankingProvinceService;

    @Autowired
    private VisitorUserService visitorUserService;

    @Override
    public void create(UserActivityTaskRankingAttach req) {
        req.setCreatedTime(new Date());
        req.setId(null);
        mongoTemplate.insert(req);
    }

    @Override
    public List<UserActivityTaskRankingAttach> find(String mobile, String activityId, String taskId) {
        log.info(":>>> 开始获取排行榜数据:{},{},{}", mobile, activityId, taskId);
        if (StringUtils.isBlank(mobile) || StringUtils.isBlank(activityId) || StringUtils.isBlank(taskId)) {
            log.error(":>>> 获取排行榜补充参数错误");
            throw new BusinessException("获取排行榜补充参数错误");
        }
        Query query = new Query().addCriteria(Criteria.where("mobile").is(mobile).and("taskId").is(taskId).and("activityId").is(activityId));
        List<UserActivityTaskRankingAttach> datas = mongoTemplate.find(query, UserActivityTaskRankingAttach.class);
        return datas;
    }

    @Override
    public Map<String, Object> dataImport(byte[] inputStream, String fileName, String activityId, String comments) {
        log.info("orderImport fileName {}", fileName);
        ActivityTaskInfo taskInfo = activityService.getTaskInfo(activityId, TaskBizType.INVITE);
        if (Objects.isNull(taskInfo)) {
            log.error(":>>> 任务不存在:{}", activityId);
            throw new BusinessException("任务不存在");
        }
        ActivityInfo activityInfo = activityService.findOne(activityId);
        Date date = new Date();
        try {
            Map<String, Object> result = new HashMap<>();
            List<UserActivityTaskRankingAttachImport> models = ExcelUtil.readData(new ByteArrayInputStream(inputStream), UserActivityTaskRankingAttachImport.class);
            result.put("allCount", models.size());
            int matchCount = 0;
            int notMatchCount = 0;
            int errorInfo = 0;
            List<Integer> notMatchRows = new ArrayList<>();
            for (int i = 0; i < models.size(); i++) {
                UserActivityTaskRankingAttachImport model = models.get(i);
                log.info(":>>> 姓名 {} 电话:{} 贡献值:{}", model.getName(), model.getMobile(), model.getQ());
                if (StringUtils.isBlank(model.getName()) || StringUtils.isBlank(model.getMobile()) || Objects.isNull(model.getQ()) ||
                        model.getMobile().length() < 10) {
                    log.error(":>>> 导入参数错误:电话、贡献值、姓名为空,手机号格式错误");
                    errorInfo++;
                    continue;
                }
                //活动加手机号 查询报名
                Query queryUser =
                        new Query().addCriteria(Criteria.where("mobile").is(model.getMobile())).addCriteria(Criteria.where("activityId").is(activityId));
                UserParticipateActivityInfo userParticipateActivityInfo = this.mongoTemplate.findOne(queryUser, UserParticipateActivityInfo.class);
                if (Objects.isNull(userParticipateActivityInfo)) {
                    continue;
                }
                //原有这种方式如果多个个账号绑定一个手机号会存在找不到情况
                //UserPO userPO = mongoTemplate.findOne(queryUser, UserPO.class);
                UserPO userPO = mongoTemplate.findById(userParticipateActivityInfo.getUserId(), UserPO.class);
                Query query = new Query().addCriteria(Criteria.where("mobile").is(model.getMobile()).and("taskId").is(taskInfo.getId()));
                UserActivityTaskRankingAttach da = mongoTemplate.findOne(query, UserActivityTaskRankingAttach.class);
                if (Objects.isNull(da)) {
                    da = new UserActivityTaskRankingAttach();
                    da.setMobile(model.getMobile());
                    da.setActivityId(activityId);
                    da.setTaskId(taskInfo.getId());
                    da.setTaskBizType(TaskBizType.INVITE);
                    da.setQuantity(model.getQ());
                    da.setCreatedTime(date);
                    if (Objects.nonNull(userPO)) {
                        da.setUserId(userPO.getId());
                    }
                    da.setComments(comments + ",导入文件:" + fileName);
                    mongoTemplate.insert(da);
                } else {
                    Update update = new Update();
                    update.inc("quantity", model.getQ());
                    update.set("updatedTime", date);
                    mongoTemplate.updateFirst(query, update, UserActivityTaskRankingAttach.class);
                }
                try {
                    if (!("h5-plus".equals(activityInfo.getType()) || "vote".equals(activityInfo.getType()) || "video".equals(activityInfo.getType()) || "qq-mini-plus-noncontest".equals(activityInfo.getType()) || "qq-mini-plus".equals(activityInfo.getType())
                            || "contest-plus".equals(activityInfo.getType()) || "qq-mini-zhongqing-contest".equals(activityInfo.getType()) || "h5++".equals(activityInfo.getType()))) {
                        log.info(":>>> 活动:{} 是老版本,修改贡献值为:{},userId:s{}", activityInfo.getName(), model.getQ(),
                                userParticipateActivityInfo.getUserId());
                        UserParticipateActivityTaskInfo userParticipateActivityTaskInfo =
                                new UserParticipateActivityTaskInfo();
                        userParticipateActivityTaskInfo.setActivityId(activityId);
                        userParticipateActivityTaskInfo.setTaskId(taskInfo.getId());
                        userParticipateActivityTaskInfo.setBizType(TaskBizType.INVITE);
                        userParticipateActivityTaskInfo.setQuantity(model.getQ());
                        // 操纵类型0:累加,1:替换
                        // 更新总榜单
                        activityService.updateUserTaskAllRanking(userPO, userParticipateActivityTaskInfo,
                                0);
                        userParticipateActivityInfo.setImportQuantityAdd(Boolean.TRUE);
                        this.mongoTemplate.save(userParticipateActivityInfo);
                    } else {
                        //增加活力值和活力值记录-新H5
                        UserActivityPointDetail userActivityPointDetail = new UserActivityPointDetail();
                        userActivityPointDetail.setAction("add");
                        userActivityPointDetail.setActivityId(activityId);
                        userActivityPointDetail.setBizDesc("其他任务");
                        userActivityPointDetail.setComments("其他任务" + model.getQ());
                        userActivityPointDetail.setBizType("other");
                        userActivityPointDetail.setOptDate(date);
                        userActivityPointDetail.setPoints(model.getQ().intValue());
                        userActivityPointDetail.setUserId(userPO.getId());
                        userActivityPointDetail.setUserPO(userPO);
                        userActivityPointDetailService.create(userActivityPointDetail);
                        //增加活力值省榜
                        userActivityPointRankingProvinceService.updatePoint(userPO, activityId,
                                model.getQ().intValue());
                    }
                } catch (Exception e) {
                    log.error("导入数据增加明显错误错误", e);
                }

            }

            result.put("matchCount", matchCount);
            result.put("notMatchCount", notMatchCount);
            result.put("notMatchRows", notMatchRows);
            result.put("errorInfo", errorInfo);
            result.put("tips", "列序号从0(A列)开始,第1列姓名(A列)、第2列(B列)手机号、第3列(C列)贡献值不能为空!");
            return result;
        } catch (Exception e) {
            log.error("orderImport error fileName {}", fileName, e);
            return null;
        }
    }

    @Override
    public List<UserActivityTaskRankingAttach> find(List<String> uid, String activityId, String taskId) {
        Query query = new Query().addCriteria(Criteria.where("userId").in(uid).and("taskId").is(taskId).and("activityId").is(activityId));
        List<UserActivityTaskRankingAttach> datas = mongoTemplate.find(query, UserActivityTaskRankingAttach.class);
        return datas;
    }

    @Override
    public UserActivityTaskRankingAttach find(String userId, String activityId) {
        Query query = new Query().addCriteria(Criteria.where("userId").is(userId).and("activityId").is(activityId));
        return mongoTemplate.findOne(query, UserActivityTaskRankingAttach.class);
    }

    @Override
    public boolean update(UserActivityTaskRankingAttach req) {
        Query query = new Query().addCriteria(Criteria.where("id").is(req.getId()));
        Update up = new Update();
        boolean toUpdate = false;
        if (Objects.nonNull(req.getQuantity())) {
            up.set("quantity", req.getQuantity());
            toUpdate = true;
        }
        if (StringUtils.isNotBlank(req.getBizTaskId())) {
            up.set("bizTaskId", req.getBizTaskId());
            toUpdate = true;
        }
        if (Objects.nonNull(req.getBizTaskDetails())) {
            up.set("bizTaskDetails", req.getBizTaskDetails());
            toUpdate = true;
        }
        if (toUpdate) {
            up.set("updatedTime", new Date());
            return mongoTemplate.updateFirst(query, up, UserActivityTaskRankingAttach.class).getModifiedCount() > 0 ? true : false;
        }
        return false;
    }

    @Override
    public List<UserActivityTaskRankingAttach> findAll(String userId, String activityId) {
        Query query = new Query().addCriteria(Criteria.where("userId").is(userId).and("activityId").is(activityId));
        return mongoTemplate.find(query, UserActivityTaskRankingAttach.class);
    }

    @Override
    public void delete(String id) {
        Query query = new Query().addCriteria(Criteria.where("id").is(id));
        mongoTemplate.remove(query,UserActivityTaskRankingAttach.class);
    }
}
